//logs.js
const util = require('../../utils/util.js');
var mqtt = require('../../utils/mqtt.min.js')
const crypto = require('../../utils/hex_hmac_sha1.js');
const DB=wx.cloud.database().collection("sersor-data");
Page({
  data: {
    logs: [],
    post_keys: [],
  
    "properties": [
      {
        "identifier": "LightLux",
        "name": "光照强度",
        "accessMode": "r",
        "required": false,
        "unit": "Lux",
        "value":32,
      },
      {
        "identifier": "SoilPH",
        "name": "土壤PH值",
        "accessMode": "r",
        "required": false,
        "value": 12,
      },
      {
        "identifier": "CH4",
        "name": "甲烷浓度",
        "accessMode": "r",
        "required": false,
        "unit": "mg/m³",
        "value": '',
      },
      {
        "identifier": "EnvironmentTemperature",
        "name": "环境温度",
        "accessMode": "r",
        "required": false,
        "unit": "°C",
        "value": '',
      },
      {
        "identifier": "SoilTemperature",
        "name": "土壤温度",
        "accessMode": "r",
        "required": false,
        "value": '',
        "unit": "°C",
      },
      {
        "identifier": "SoilMoisture",
        "name": "土壤湿度",
        "accessMode": "r",
        "unitName": "百分比",
        "required": false,  
        "value": '',
        "unit": "°C",
      }
    ]
      },
    
  

  onLoad: function () {
    var that = this
    const deviceConfig = {
      productKey: 'a1cHvZF1Pqk',
      deviceName: 'sensor-data',
      deviceSecret: 'EjaVShFYLsOmjoq2vhUXujt7iRU7jZzu',
      regionId: "cn-shanghai"
    };
    const options = this.initMqttOptions(deviceConfig);
    console.log(options)
    //替换productKey为你自己的产品的
    const client = mqtt.connect('wxs://a1cHvZF1Pqk.iot-as-mqtt.cn-shanghai.aliyuncs.com', options)
    client.on('connect', function () {
      console.log('连接服务器成功')
      //订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看后台设备Topic列表或使用自定义主题)
      client.subscribe('/a1cHvZF1Pqk/sensor-data/user/set?_sn=default', function (err) {
        if (!err) {
          console.log('订阅成功！');
              //接收消息监听const 
        }
      })
      var result = client.on('message', function (topic, message) {
        // message is Buffer
        //不要漏了这句，很重要
        console.log('收到消息:' + message.toString());
        var result = JSON.parse(message)

        that.setData({
          list: result
        })
      })

      client.subscribe('/a1cHvZF1Pqk/sensor-data/user/get?_sn=default', function (err) {
        if (!err) {
          console.log('订阅成功！');  
        }
      })
      var result = client.on('message', function (topic, message) {
        // message is Buffer
        //不要漏了这句，很重要
        console.log('收到消息11:' + message.toString());
        var result = JSON.parse(message)
        const db = wx.cloud.database().collection("sersor-data");
        DB.add({
          data:{result},
          success(res){
            console.log("添加成功",res)
          }, 
        fail(res){
          console.log("添加失败", res)
        }
          })

      })

    })
  },

  //IoT平台mqtt连接参数初始化
  initMqttOptions(deviceConfig) {

    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;
    return options;
  },

  /*
    生成基于HmacSha1的password
    参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
  */
  signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  }

  
})











